#include "comM.hpp"
#include "log.hpp"
#include <iostream>
#include <string>
#include <cstdio>
#include <unistd.h>

extern Log log; // 开启日志

int main()
{
    // 创建并链接共享内存
    int shmid = CreateShm();
    char *shmaddr = (char *)shmat(shmid, nullptr, 0);

    // 创建并打开命名管道
    Init init;  
    int fd = open(FIFO_FILE, O_RDONLY);
    if (fd < 0)
    {
        log(Fatal, "open errno: %s, errno code: %d", strerror(errno), errno);
        exit(FIFO_OPEN_ERR);
    }

    // IPC Code
    while (true)
    {
        // std::string buffer;
        // ssize_t n = read(fd, &buffer[0], 1024);
        // if (strlen(buffer.c_str()) < 0)  break;
        // else if (strlen(buffer.c_str()) == 0)  break;
        char c;
        ssize_t s = read(fd, &c, 1);
        if(s == 0) break;
        else if(s < 0) break;

        std::cout << "client say@ " << shmaddr;  // 直接访问共享内存
        sleep(1);

        shmid_ds shmds;  // 用来保存share memory的属性
        shmctl(shmid, IPC_STAT, &shmds);    // 保存share memory的属性
        std::cout << "shm size: " << shmds.shm_segsz << std::endl;
        std::cout << "shm nattch: " << shmds.shm_nattch << std::endl;
        printf("shm key: 0x%x\n",  shmds.shm_perm.__key);
        std::cout << "shm mode: " << shmds.shm_perm.mode << std::endl;
    }

    shmdt(shmaddr);
    shmctl(shmid, IPC_RMID, nullptr);  // ipcrm -m
    close(fd);
    return 0;
}